package com.idea.easy.log.listener;

import com.idea.easy.log.model.ErrorLog;
import com.idea.easy.log.provider.EasyLogInfoUtil;
import com.idea.easy.log.provider.EasyLogServerInfoProvider;
import com.idea.easy.log.event.ErrorLogEvent;
import com.idea.easy.log.model.ErrorLogModel;
import com.idea.easy.log.props.EasyLogProperties;
import com.idea.easy.log.provider.SpringAware;
import com.idea.easy.log.service.IEasyLogService;
import com.idea.easy.log.service.mp.IErrorLogService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.util.Assert;

/**
 * @className: ErrorLogListener
 * @description: 错误日志事件的监听
 * @author: salad
 * @date: 2022/6/9
 **/
@Slf4j
@AllArgsConstructor
public class ErrorLogListener{

    private final EasyLogProperties properties;

    private final EasyLogServerInfoProvider serverInfoProvider;

    @Async
    @EventListener(ErrorLogEvent.class)
    public void listener(ErrorLogEvent event) {
        ErrorLogModel errorLogModel = (ErrorLogModel)event.getSource();
        //向实体类中增加额外的信息
        EasyLogInfoUtil.appendServerInfo(errorLogModel, serverInfoProvider, properties);
        //向IOC容器中寻找Bean
        IErrorLogService errorLogService = SpringAware.getBean(IErrorLogService.class);
        if (errorLogService != null){
            ErrorLog errorLog = new ErrorLog();
            BeanUtils.copyProperties(errorLogModel,errorLog);
            errorLog.setErrorFileName(errorLogModel.getErrorFileName())
                    .setErrorName(errorLogModel.getErrorName());
            errorLog.setErrorLineNumber(errorLogModel.getErrorLineNumber())
                    .setErrorMessage(errorLogModel.getErrorMessage());
            errorLogService.saveErrorLog(errorLog);
        } else {
            IEasyLogService easyLogService = SpringAware.getBean(IEasyLogService.class);
            Assert.notNull(easyLogService,"easy-log: 为了存储日志数据,需要实现 IErrorLogService 或者 IEasyLogService 接口");
            easyLogService.saveErrorLog(errorLogModel);
        }

    }

}